<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Admin\Metrics\Examples;

use App\Admin\Metrics\DatepickerTrait;
use App\Models\GroupOrder;
use App\Models\ProductOrder;
use Dcat\Admin\Widgets\Metrics\RadialBar;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class Tickets extends RadialBar
{
    use DatepickerTrait;

    public $productOrderModel;

    public $groupOrderModel;

    public function __construct()
    {
        parent::__construct();
        $this->productOrderModel = ProductOrder::query()->select(['created_at', 'total_amount', 'status'])->where('status', '>', 1)->get();
        $this->groupOrderModel = GroupOrder::query()->select(['created_at', 'amount', 'status'])->where('status', '>', 2)->get();
    }

    /**
     * 处理请求
     *
     * @return mixed|void
     */
    public function handle(Request $request)
    {
        if ($request->has('started')) {
            $res = $this->calculation(
                now()->setDateFrom(
                    $request->get('started')
                )->startOfDay(),
                now()->setDateFrom($request->get('ended'))->endOfDay()
            );
        } else {
            switch ($request->get('option')) {
                case '7':
                    $res = $this->calculation(now()->startOfWeek(), now()->endOfDay());
                    $this->withContent($res['content']);
                    break;
                case '30':
                    //月
                    $res = $this->calculation(now()->startOfMonth(), now()->endOfDay());
                    $this->withContent($res['content']);
                    break;
                case '90':
                    $res = $this->calculation(now()->startOfQuarter(), now()->endOfDay());
                    $this->withContent($res['content']);
                    break;
                case '365':
                    $res = $this->calculation(now()->startOfYear(), now()->endOfDay());
                    $this->withContent($res['content']);
                    break;
                case '0':
                    $res = $this->calculation(now()->startOfDay(), now()->endOfDay());
                    $this->withContent($res['content']);
                    break;
                case '999':
                    $res = $this->calculation(now()->startOfDecade(), now()->endOfDay());
                    break;
                default:
                    $res = $this->calculation(now()->startOfDay(), now()->endOfDay());
                    $this->withContent($res['content']);
                    break;
            }
        }
        // 卡片内容

        // 卡片底部
        $this->withFooter(...$res['footer']);
        // 图表数据
        $this->withChart($res['chart']);
    }

    /**
     * 设置图表数据.
     *
     * @return $this
     */
    public function withChart(int $data)
    {
        return $this->chart([
            'series' => [$data],
        ]);
    }

    /**
     * 卡片内容.
     *
     * @param string $content
     *
     * @return $this
     */
    public function withContent($content)
    {
        return $this->content(
            <<<HTML
<div class=" flex-column flex-wrap ">
    <small >{$content}</small>
</div>
HTML
        );
    }

    /**
     * 卡片底部内容.
     *
     * @param string $new
     * @param string $open
     * @param string $response
     *
     * @return $this
     */
    public function withFooter($new, $open, $response)
    {
        return $this->footer(
            <<<HTML
<div class="d-flex justify-content-between p-1" style="padding-top: 0!important;">
    <div class="text-center">
        <p>总销售额</p>
        <span class="font-lg-1">{$new}</span>
    </div>
    <div class="text-center">
        <p>商品销售</p>
        <span class="font-lg-1">{$open}</span>
    </div>
    <div class="text-center">
        <p>拼团销售</p>
        <span class="font-lg-1">{$response}</span>
    </div>
</div>
HTML
        );
    }

    /**
     * 初始化卡片内容.
     */
    protected function init()
    {
        parent::init();

        $this->title('销售额');
        $this->height(400);
        $this->chartHeight(300);
        $this->chartLabels('销售额占比');
        $this->dropdown([
            '0' => '今日',
            '7' => '周',
            '30' => '月',
            '90' => '季度',
            '365' => '年',
            '999' => '全部',
        ]);
        $id = $this->id();
        $this->datepicker($id)
            ->click("#{$id} .datepicker .btn-primary")
            ->addVariables([
                'datepicker' => [
                    'start' => date('Y-m-d', strtotime('-7 days')),
                    'end' => date('Y-m-d', time()),
                ],
            ]);
    }

    private function calculation(Carbon $start, Carbon $end)
    {
        $total = bcadd(
            $this->productOrderModel->sum('total_amount'),
            $this->groupOrderModel->sum('amount'),
            2
        );
        if ($total == 0) {
            $total = 1;
        }

        $nowTotal = bcadd(
            $this->productOrderModel->whereBetween('created_at', [$start, $end])
                ->sum('total_amount'),
            $this->groupOrderModel->whereBetween('created_at', [$start, $end])
                ->sum('amount'),
            2
        );
        return [
            'content' => sprintf('%s - %s', $start->toDateString(), $end->toDateString()),
            'footer' => [
                $nowTotal,
                $this->productOrderModel->whereBetween('created_at', [$start, $end])
                    ->sum('total_amount'),
                $this->groupOrderModel->whereBetween('created_at', [$start, $end])
                    ->sum('amount'),
            ],
            'chart' => bcdiv($nowTotal, $total, 2) * 100,
        ];
    }
}
